package com.sso.server.config;

import com.sso.server.security.SystemUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author songyouchao
 * @ClassName SecurityConfig.java
 * @Description
 * @createTime 2021年08月15日
 */
@Configuration
@EnableWebSecurity
@Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    SystemUserDetailService userDetailService;

    @Bean
    PasswordEncoder getPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService).passwordEncoder(getPasswordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/oauth/check_token", "/user/login");
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/authentication/*", "logout","/css/**","/font/**","/images/**","/plugins/**","/scripts/**","/auth/login","/oauth/**") // 不需要登录就可以访问
                .permitAll()
                .antMatchers("/gate-way/**").hasAnyRole("admin") // 需要具有ROLE_USER角色才能访问
                .anyRequest().authenticated()
                .and()
                .logout()
                .logoutUrl("/user/logout")
                .logoutSuccessHandler((HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) -> {
                    httpServletResponse.sendRedirect("/authentication/loginPage");
                }) // 设置退出处理器
                .and()
                .formLogin()
                .loginPage("/authentication/loginPage")
                .successForwardUrl("http://localhost:18000/gate-way/success")
                //.loginProcessingUrl("/authentication/success") //登录发起的post请求方法
/*                .successHandler((HttpServletRequest request, HttpServletResponse response,
                                 Authentication authentication) ->{
                    response.setContentType("application/json;charset=utf-8");

                    RequestCache cache = new HttpSessionRequestCache();
                    SavedRequest savedRequest = cache.getRequest(request, response);
                    String url = savedRequest.getRedirectUrl();
                    if(StringUtils.isEmpty(url)){
                        url = "/authentication/success";
                    }
                    response.sendRedirect(url);

                }) //登录成功页面*/
                .failureForwardUrl("/authentication/fail"); //无权限页面


    }
}
